//
//  AppDelegate.m
//  XSJ
//
//  Created by apple on 28.4.20.
//  Copyright © 2020 apple. All rights reserved.
//

#import "AppDelegate.h"
#import "SVProgressHUD.h"
#import "TabBarControllerConfig.h"
#import "BaseNaviViewController.h"
#import "XSJLoginVC.h"
#import "HttpTool.h"
#import "XSJTool.h"
#import "UserInfoModel.h"
#import <IQKeyboardManager.h>


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //设置svp最小时间
    [SVProgressHUD setMinimumDismissTimeInterval:1.0f];
    
    // 设置键盘manager
    //点击背景收回键盘
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    //设置主域名
    HttpTool *httptool = [HttpTool sharedManager];
    [httptool setMainUrl:MainUrl];
    
    [self to_MainVC];
    [self BaseSetup];
    
    // 设置网易云信
    //[self setNIMSDK];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    //清除角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //网易云登录判断
    //[self loginNIM];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //iOS13 deviceToken的数据结构改变，需要更改取值方法
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    
    NSData *data = [hexToken dataUsingEncoding:NSUTF8StringEncoding];
    
    //[[NIMSDK sharedSDK] updateApnsToken:data];
}


//跳到登录界面
-(void)to_LoginVC
{
    XSJLoginVC *loginVC = [[XSJLoginVC alloc] init];
    BaseNaviViewController *navController = [[BaseNaviViewController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = navController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //判断网易云是否登出
    [self logoutNIM];
}

//根据用户信息选择主界面
-(void)to_MainVC
{
    //判断用户信息是否存在
    UserInfoModel* userInfo = [UserInfoModel readUserInfo];
    if (kObjectIsEmpty(userInfo))
    {
        [self to_LoginVC];
    }
    else
    {
        [self to_HomeVC];
    }
}

//跳到主界面
-(void)to_HomeVC
{
    TabBarControllerConfig *tabBarControllerConfig = [[TabBarControllerConfig alloc] init];
    //注册加号按钮
    [tabBarControllerConfig regPlusButton];
    BaseTabBarController *tabBarController = tabBarControllerConfig.tabBarController;
    [self.window setRootViewController:tabBarController];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
}


-(void)BaseSetup
{
    //用户登录注册成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUserLoginRegisterNotification:) name:UserLoginRegisterNotification object:nil];
    
    //状态栏的文字颜色(Info.plist 文件中添加 View controller-based status bar appearance 设置为 NO)
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    //    // 导航条上标题的颜色字体
    //    [UINavigationBar appearance].titleTextAttributes = @{
    //                                                         NSForegroundColorAttributeName : [UIColor whiteColor],
    //                                                         NSFontAttributeName : [UIFont systemFontOfSize:18]
    //                                                         };
    //导航条上UIBarButtonItem颜色
    [UINavigationBar appearance].tintColor = [UIColor blackColor];
    //导航条的背景颜色
    [[UINavigationBar appearance] setBackgroundImage:[XSJTool Color2Image:[UIColor whiteColor]] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
}


//用户登录注册成功
- (void)handleUserLoginRegisterNotification:(NSNotification *)notification
{
    //进入主界面
    [self to_HomeVC];
}


- (void)setNIMSDK
{
    //在注册 NIMSDK appKey 之前先进行配置信息的注册，如是否使用新路径,是否要忽略某些通知，是否需要多端同步未读数等
//    self.sdkConfigDelegate = [[NTESSDKConfigDelegate alloc] init];
//    [[NIMSDKConfig sharedConfig] setDelegate:self.sdkConfigDelegate];
//    [[NIMSDKConfig sharedConfig] setShouldSyncUnreadCount:YES];
//    [[NIMSDKConfig sharedConfig] setMaxAutoLoginRetryTimes:10];
//    [[NIMSDKConfig sharedConfig] setMaximumLogDays:[[NTESBundleSetting sharedConfig] maximumLogDays]];
//    [[NIMSDKConfig sharedConfig] setShouldCountTeamNotification:[[NTESBundleSetting sharedConfig] countTeamNotification]];
    
    //appkey 是应用的标识，不同应用之间的数据（用户、消息、群组等）是完全隔离的。
    //如需打网易云信 Demo 包，请勿修改 appkey ，开发自己的应用时，请替换为自己的 appkey 。
    //并请对应更换 Demo 代码中的获取好友列表、个人信息等网易云信 SDK 未提供的接口。
//    NIMSDKOption *option    = [NIMSDKOption optionWithAppKey:NIMSDK_APPKEY];
//    option.apnsCername      = NIMSDK_CERNAME;
//    option.pkCername        = NIMSDK_CERNAME;
//    [[NIMSDK sharedSDK] registerWithOption:option];
//
//    [[NIMSDK sharedSDK] registerWithAppID:NIMSDK_APPKEY
//                                  cerName:NIMSDK_CERNAME];
//
//    //注册自定义消息的解析器
//    [NIMCustomObject registerCustomDecoder:[NTESCustomAttachmentDecoder new]];
//
//    //注册 NIMKit 自定义排版配置
//    [[NIMKit sharedKit] registerLayoutConfig:[NTESCellLayoutConfig new]];
//
//    //启动通知
//    [[NTESNotificationCenter sharedCenter] start];
//
//    //开启视频录制
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"server_record_video"];
//    //开启音频录制
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"server_record_audio"];
//    //同步
//    [[NSUserDefaults standardUserDefaults] synchronize];
//
//    //判断网易云是否登录
//    [self loginNIM];
}

//登录网易云
-(void)loginNIM
{
//    if (![[[NIMSDK sharedSDK] loginManager] isLogined])
//    {
//        UserInfoModel* userInfo = [UserInfoModel readUserInfo];
//        if ( !kStringIsEmpty(userInfo.uid) && !kStringIsEmpty(userInfo.im_token))
//        {
//            //自动登录IM
//            [[[NIMSDK sharedSDK] loginManager] autoLogin:userInfo.uid token:userInfo.im_token];
//        }
//    }
}

//登出网易云
-(void)logoutNIM
{
//    if ([[[NIMSDK sharedSDK] loginManager] isLogined])
//    {
//        [[[NIMSDK sharedSDK] loginManager] logout:^(NSError * _Nullable error)
//        {
//            //退出IM
//            if (error)
//            {
//                DLog(@"%@",error.domain);
//            }
//            else
//            {
//                DLog(@"退出IM成功");
//            }
//        }];
//    }
}



@end
